/* eslint-disable no-unused-vars */
import axios, { AxiosRequestConfig } from 'axios';
import store from '@/vuex/index';
import router from '@/router/index';

// process.env.NODE_ENV环境
let baseURL;
if (process.env.NODE_ENV === 'development') {
  baseURL = 'http://localhost:3000';
} else {
  baseURL = 'http://localhost:3000';
}

export const ServeURL = baseURL;

// baseURL es6 方法

const $http = axios.create({
  baseURL,
});
// create 是axios自带的方法

// 允许跨域携带cookie信息
$http.defaults.withCredentials = true;

$http.interceptors.response.use(
  (response) => {
    // 拦截响应，做统一处理
    if (response.data?.code === 301) {
      store.commit('setLoginDialogVisible', true);
      store.commit('setPrevPath', router.currentRoute.fullPath);
      router.replace('/');
    }
    return response;
  },
  // 接口错误状态处理，也就是说无响应时的处理
  (error) => {
    if (error.response.data?.code === 301) {
      store.commit('app/setLoginDialogVisible', true);
      store.commit('app/setPrevPath', router.currentRoute.fullPath);
      router.replace('/');
    }
    return Promise.reject(error);
  }
);

$http.interceptors.request.use(
  config => {
    const cookie = sessionStorage.getItem('cookie')
    if (cookie && cookie !== "undefined") {
      if (config.method?.toLowerCase() === "post") {
        config.data = {
          cookie,
          ...config.data
        };
      } else {
        config.params = {
          cookie,
          ...config.params
        };
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

export const get = <T>(
  url: string,
  params?: object,
  config?: AxiosRequestConfig
) => {
  params = params || {};
  return new Promise<T>((resolve, reject) => {
    $http
      .get(url, {
        params,
        ...(config ?? {}),
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export const post = <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
) => {
  data = data || {};
  return new Promise<T>((resolve, reject) => {
    $http
      .post(url, data, config)
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export default {
  get,
  post,
};
